package org.yangjie.cipher;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 对称加密AES
 * @author YangJie [2017年10月10日 下午3:58:10]
 */
public class AESUtil {
	
	/** 密钥 */
	private static final String KEY = "ax56bf32hp54kt68";
	

	/**
	 * 加密
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String str) throws Exception {
		return Base64.getEncoder().encodeToString(aes(str.getBytes("utf-8"), Cipher.ENCRYPT_MODE));
	}
	
	/**
	 * 解密
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String str) throws Exception {
		return new String(aes(Base64.getDecoder().decode(str), Cipher.DECRYPT_MODE), "utf-8");
	}
	
	/**
	 * 执行aes算法
	 * @param bytes 
	 * @param opmode 工作模式 (Cipher.ENCRYPT_MODE/Cipher.DECRYPT_MODE)
	 * @return
	 * @throws Exception
	 */
	public static byte[] aes(byte[] bytes, int mode) throws Exception {
		SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES"); // 密钥
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 指定加密的算法、工作模式和填充方式
		cipher.init(mode, secretKeySpec);
		return cipher.doFinal(bytes);
	}

	
	public static void main(String[] args) throws Exception {

		String str = "hello world";
		
		// 加密
		String encryptedString = encrypt(str);
		System.out.println("加密后：" + encryptedString);

		// 解密
		String decryptedString = decrypt(encryptedString);
		System.out.println("解密后：" + new String(decryptedString));
		
	}
	
}
